package com.esm.tool;

import android.annotation.SuppressLint;
import android.content.ContentResolver;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;
import android.content.res.Resources;
import android.database.Cursor;
import android.location.LocationManager;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.os.Environment;
import android.provider.MediaStore.Images.ImageColumns;
import android.text.Html;
import android.text.Spanned;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.esm.app.MyApplication;
import com.esm.view.R;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

@SuppressLint("SimpleDateFormat")
public class Utils {
    /**
     * “android.intent.action.MEDIA_SCANNER_SCAN_DIR”：扫描指定目录
     */
    public static final String ACTION_MEDIA_SCANNER_SCAN_DIR = "android.intent.action.MEDIA_SCANNER_SCAN_DIR";
    @SuppressWarnings("unused")
    private static final double PI = 3.14159265;
    private static final double RAD = Math.PI / 180.0;
    private static final double EARTH_RADIUS = 6378137.0;
    public static SimpleDateFormat DB_TIMESTAMP_Format = new SimpleDateFormat("yyyy-MM-dd HH:mm");
    public static SimpleDateFormat LOCATION_Format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    private static Toast toast2;

    // 返回单位是米
    public static double getDistance(double longitude1, double latitude1, double longitude2, double latitude2) {
        double Lat1 = rad(latitude1);
        double Lat2 = rad(latitude2);
        double a = Lat1 - Lat2;
        double b = rad(longitude1) - rad(longitude2);
        double s = 2 * Math.asin(Math
                .sqrt(Math.pow(Math.sin(a / 2), 2) + Math.cos(Lat1) * Math.cos(Lat2) * Math.pow(Math.sin(b / 2), 2)));
        s = s * EARTH_RADIUS;
        s = Math.round(s * 10000) / 10000;
        return s;
    }

    public static long transDateStringToLong6(String time) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        try {
            return sdf.parse(time).getTime();
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return 0;
    }

    public static String transLongToDateString(long time) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm");
        Date date = new Date(time);
        return sdf.format(date);
    }

    public static String transLongToDateString5(long time) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        Date date = new Date(time);
        return sdf.format(date);
    }

    public static String transLongToDateString3(long time) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date date = new Date(time);
        return sdf.format(date);
    }

    public static File getOutputMediaStorageDir2() {
        File mediaStorageDir = new File(getPath());
        if (!mediaStorageDir.exists()) {
            if (!mediaStorageDir.mkdirs()) {
                return null;
            }
        }
        return mediaStorageDir;
    }

    public static String getPath() {
        String path = null;
        String packageName = "/" + MyApplication.packagename + "/";
        if (Environment.getExternalStorageState().equals(android.os.Environment.MEDIA_MOUNTED)) {// 判断sd卡是否存
            path = Environment.getExternalStorageDirectory().getAbsolutePath() + packageName;
        } else {
            path = Environment.getRootDirectory().getAbsolutePath() + packageName;
        }
        File file = new File(path);
        boolean isExist = file.exists();
        if (!isExist) {
            file.mkdirs();
        }
        return file.getPath();
    }

    public static void makeRootDirectory(String filePath) {
        File file = null;
        String newPath = null;
        String[] path = filePath.split("/");
        for (int i = 0; i < path.length; i++) {
            if (newPath == null) {
                newPath = path[i];
            } else {
                newPath = newPath + "/" + path[i];
            }
            file = new File(newPath);
            if (!file.exists()) {
                file.mkdir();
            }
        }
    }

    public static String transLongToDateString2(long time) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy年MM月dd日");
        Date date = new Date(time);
        return sdf.format(date);
    }

    public static long transDateStringToLong(String time) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm");
        try {
            return sdf.parse(time).getTime();
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return 0;
    }

    public static long transDateStringToLong5(String time) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        try {
            return sdf.parse(time).getTime();
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return 0;
    }

    public static long transDateStringToLong2(String time) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd");
        try {
            return sdf.parse(time).getTime();
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return 0;
    }

    // public static String getVersion() {
    // String version = "";
    // try {
    // PackageManager manager = KindergartenApplication.getInstance()
    // .getApplicationContext().getPackageManager();
    // PackageInfo info = manager.getPackageInfo(KindergartenApplication
    // .getInstance().getApplicationContext().getPackageName(), 0);
    // version = info.versionName;
    // } catch (Exception e) {
    // e.printStackTrace();
    // }
    // return version;
    // }

    /**
     * 根据两点间经纬度坐标（double值），计算两点间距离，单位为
     *
     * @param lng1
     * @param lat1
     * @param lng2
     * @param lat2
     * @return
     */
    public static double getBaiduDistance(double lng1, double lat1, double lng2, double lat2) {
        double radLat1 = lat1 * RAD;
        double radLat2 = lat2 * RAD;
        double a = radLat1 - radLat2;
        double b = (lng1 - lng2) * RAD;
        double s = 2 * Math.asin(Math.sqrt(
                Math.pow(Math.sin(a / 2), 2) + Math.cos(radLat1) * Math.cos(radLat2) * Math.pow(Math.sin(b / 2), 2)));
        s = s * EARTH_RADIUS;
        s = Math.round(s * 10000) / 10000;
        System.out.println(s);
        return s;
    }

    private static double rad(double d) {
        return d * Math.PI / 180.0;
    }

    public static int getUid(Context context) {
        try {
            PackageManager pm = context.getPackageManager();
            @SuppressLint("WrongConstant") android.content.pm.ApplicationInfo ai = pm.getApplicationInfo("com.ugoodtech.android.kindergarten",
                    PackageManager.GET_ACTIVITIES);
            Log.d("!!", "!!" + ai.uid);
            return ai.uid;
        } catch (android.content.pm.PackageManager.NameNotFoundException e) {
            e.printStackTrace();
            return -1;
        }
    }

    public static void scanDirAsync(Context ctx, String dir) {
        Intent scanIntent = new Intent(ACTION_MEDIA_SCANNER_SCAN_DIR);
        scanIntent.setData(Uri.fromFile(new File(dir)));
        ctx.sendBroadcast(scanIntent);
    }

    /**
     * 启动MediaScanner服务，扫描媒体文件： 程序通过发�?�下面的Intent启动MediaScanner服务扫描指定的文件或目录�??
     * <p>
     * Intent.ACTION_MEDIA_SCANNER_SCAN_FILE：扫描指定文�??
     *
     * @param ctx
     * @param filePath
     */

    public static void scanFileAsync(Context ctx, String filePath) {
        Intent scanIntent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
        scanIntent.setData(Uri.fromFile(new File(filePath)));
        ctx.sendBroadcast(scanIntent);
    }

    /**
     * 返回当前程序版本�??
     */
    public static String getAppVersionName(Context context) {
        String versionName = "";
        try {
            // ---get the package info---
            PackageManager pm = context.getPackageManager();
            PackageInfo pi = pm.getPackageInfo(context.getPackageName(), 0);
            versionName = pi.versionName;
            // versioncode = pi.versionCode;
            if (versionName == null || versionName.length() <= 0) {
                return "";
            }
        } catch (Exception e) {
            Log.e("VersionInfo", "Exception", e);
        }
        return versionName;
    }

    public static int compare(String v1, String v2) {
        String s1 = normalisedVersion(v1);
        String s2 = normalisedVersion(v2);
        return s1.compareTo(s2);
    }

    public static String normalisedVersion(String version) {
        return normalisedVersion(version, ".", 4);
    }

    public static String normalisedVersion(String version, String sep, int maxWidth) {
        String[] split = Pattern.compile(sep, Pattern.LITERAL).split(version);
        StringBuilder sb = new StringBuilder();
        for (String s : split) {
            sb.append(String.format("%" + maxWidth + 's', s));
        }
        return sb.toString();
    }

    public static boolean checkpwd(String pwd) {

        Pattern p = Pattern.compile("[0-9A-Za-z]*");

        Matcher m = p.matcher(pwd);

        System.out.println(m.matches() + "---");

        return m.matches();

    }

    public static boolean isSDCardExist() {
        return Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED);
    }

    public static File getWorkDir() {
        File dir = null;
        try {
            String destDir = Environment.getExternalStorageDirectory().getPath() + File.separator + "FmsAndroid";
            dir = new File(destDir);
        } catch (Exception x) {
            dir = Environment.getDownloadCacheDirectory();
        }
        if (!dir.exists())
            dir.mkdirs();
        return dir;
    }

    public static void showToast(Context context, String text) {
        Toast.makeText(context, text, Toast.LENGTH_SHORT).show();
    }

    public static void showToast(Context context, int resId) {
        Toast.makeText(context, context.getResources().getString(resId), Toast.LENGTH_SHORT).show();
    }

    public static String getRefreshTime() {
        return DB_TIMESTAMP_Format.format(new Date());
    }

    public static String getStandardTime() {
        return LOCATION_Format.format(new Date());
    }

    public static boolean isMobileNO(String mobiles) {
        Pattern p = Pattern.compile("^((13[0-9])|(15[^4,\\D])|(18[0-9]))\\d{8}$");
        Matcher m = p.matcher(mobiles);
        return m.matches();
    }

    public static void hideSystemKeyBoard(Context context, View view) {
        InputMethodManager imm = (InputMethodManager) context.getSystemService(Context.INPUT_METHOD_SERVICE);
        imm.hideSoftInputFromWindow(view.getWindowToken(), 0);
    }

    public static void showSystemKeyBoard(Context context, View view) {
        InputMethodManager imm = (InputMethodManager) context.getSystemService(Context.INPUT_METHOD_SERVICE);
        imm.showSoftInput(view, 0);
    }

    public static boolean isNetworkConnected(Context context) {
        if (context != null) {
            ConnectivityManager mConnectivityManager = (ConnectivityManager) context
                    .getSystemService(Context.CONNECTIVITY_SERVICE);
            NetworkInfo mNetworkInfo = mConnectivityManager.getActiveNetworkInfo();
            if (mNetworkInfo != null) {
                return mNetworkInfo.isAvailable();
            }
        }
        return false;
    }

    public static boolean toastIsNetworkConnected(Context context) {
        boolean l = isNetworkConnected(context);
        return l;
        // Toast.makeText(context, "网络连接不可�??", Toast.LENGTH_SHORT).show();
    }

    public static void focusOnError(Context context, TextView field, int resourceId) {
        field.requestFocus();
        hideSystemKeyBoard(context, field);
        field.setError("<font color=#333333>" + context.getString(resourceId) + "</font>");
    }

    public static void focusOnError(Context context, EditText field, String message) {
        field.requestFocus();
        hideSystemKeyBoard(context, field);
        Spanned fromHtml = Html.fromHtml("<font color=#333333>" + message + "</font>");
        field.setError(fromHtml);
        // field.clearFocus();
    }

    /**
     * Create a file Uri for saving an image or video
     */
    public static Uri getOutputMediaFileUri() {
        File mediaFile = getOutputMediaFile();
        if (mediaFile == null) {
            return null;
        } else {
            return Uri.fromFile(mediaFile);
        }
    }

    public static File getOutputMediaStorageDir() {
        // To be safe, you should check that the SDCard is mounted
        // using Environment.getExternalStorageState() before doing this.
        File mediaStorageDir = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES),
                "p009");

        if (!mediaStorageDir.exists()) {
            if (!mediaStorageDir.mkdirs()) {
                return null;
            }
        }
        return mediaStorageDir;
    }

    /**
     * Create a File for saving an image or video
     */
    public static File getOutputMediaFile() {
        File mediaStorageDir = getOutputMediaStorageDir();
        // Create a media file name
        String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
        File mediaFile = new File(mediaStorageDir.getPath() + File.separator + "IMG_" + timeStamp + ".jpg");
        Log.d("kindergarten", "temp path:" + mediaFile.getPath());
        return mediaFile;
    }

    public static String getSDPath() {
        File sdDir = null;
        boolean sdCardExist = Environment.getExternalStorageState().equals(android.os.Environment.MEDIA_MOUNTED); // 判断sd卡是否存�??
        if (sdCardExist) {
            sdDir = Environment.getExternalStorageDirectory();// 获取跟目�??
        } else {
            sdDir = Environment.getRootDirectory();
        }
        return sdDir.toString();

    }

    public static boolean createDir(String destDirName) {
        File dir = new File(destDirName);
        if (dir.exists()) {
            System.out.println("创建目录" + destDirName + "失败，目标目录已经存�??");
            return false;
        }
        if (!destDirName.endsWith(File.separator)) {
            destDirName = destDirName + File.separator;
        }
        // 创建目录
        if (dir.mkdirs()) {
            System.out.println("创建目录" + destDirName + "成功");
            return true;
        } else {
            System.out.println("创建目录" + destDirName + "失败");
            return false;
        }
    }

    public static String getVersion() {
        String version = "";
        try {
            PackageManager manager = MyApplication.getInstance().getApplicationContext().getPackageManager();
            PackageInfo info = manager
                    .getPackageInfo(MyApplication.getInstance().getApplicationContext().getPackageName(), 0);
            version = info.versionName;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return version;
    }

    public static int getVersionCode() {
        int version = 0;
        try {
            PackageManager manager = MyApplication.getInstance().getApplicationContext().getPackageManager();
            PackageInfo info = manager
                    .getPackageInfo(MyApplication.getInstance().getApplicationContext().getPackageName(), 0);
            version = info.versionCode;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return version;
    }

    public static String standardImageUrlSuoFangpx(String url, int width) {
        return url + "@" + width + "w";
    }

    public static String standardImageUrlPX(String url, int width, int height) {
        return url + "@" + width + "w_" + height + "h_1e_1c";
    }

    /**
     * 根据手机的分辨率�?? dp 的单�?? 转成�?? px(像素)
     */
    public static int dip2px(Context context, float dpValue) {
        final float scale = context.getResources().getDisplayMetrics().density;
        return (int) (dpValue * scale + 0.5f);
    }

    public static int dip2px(Context context, double dpValue) {
        final float scale = context.getResources().getDisplayMetrics().density;
        return (int) (dpValue * scale + 0.5f);
    }

    /**
     * 根据手机的分辨率�?? px(像素) 的单�?? 转成�?? dp
     */
    public static int px2dip(Context context, float pxValue) {
        final float scale = context.getResources().getDisplayMetrics().density;
        return (int) (pxValue / scale + 0.5f);
    }

    /**
     * 删除目录（文件夹）以及目录下的文�??
     *
     * @param sPath 被删除目录的文件路径
     * @return 目录删除成功返回true，否则返回false
     */
    public static boolean deleteDirectory(String sPath) {
        // 如果sPath不以文件分隔符结尾，自动添加文件分隔�??
        if (!sPath.endsWith(File.separator)) {
            sPath = sPath + File.separator;
        }
        File dirFile = new File(sPath);
        // 如果dir对应的文件不存在，或者不是一个目录，则�??�??
        if (!dirFile.exists() || !dirFile.isDirectory()) {
            return false;
        }
        boolean flag = true;
        // 删除文件夹下的所有文�??(包括子目�??)
        File[] files = dirFile.listFiles();
        for (int i = 0; i < files.length; i++) {
            // 删除子文�??
            if (files[i].isFile()) {
                flag = deleteFile(files[i].getAbsolutePath());
                if (!flag)
                    break;
            } // 删除子目�??
            else {
                flag = deleteDirectory(files[i].getAbsolutePath());
                if (!flag)
                    break;
            }
        }
        if (!flag)
            return false;
        // 删除当前目录
        return dirFile.delete();
    }

    /**
     * 删除目录（文件夹）下的文�??
     *
     * @param sPath 被删除目录的文件路径
     * @return 目录删除成功返回true，否则返回false
     */
    public static boolean deleteDirectorySon(String sPath) {
        // 如果sPath不以文件分隔符结尾，自动添加文件分隔�??
        if (!sPath.endsWith(File.separator)) {
            sPath = sPath + File.separator;
        }
        File dirFile = new File(sPath);
        // 如果dir对应的文件不存在，或者不是一个目录，则�??�??
        if (!dirFile.exists() || !dirFile.isDirectory()) {
            return false;
        }
        boolean flag = true;
        // 删除文件夹下的所有文�??(包括子目�??)
        File[] files = dirFile.listFiles();
        for (int i = 0; i < files.length; i++) {
            // 删除子文�??
            if (files[i].isFile()) {
                flag = deleteFile(files[i].getAbsolutePath());
                if (!flag)
                    break;
            } // 删除子目�??
            else {
                flag = deleteDirectory(files[i].getAbsolutePath());
                if (!flag)
                    break;
            }
        }
        return flag;
    }

    /**
     * 删除单个文件
     *
     * @param sPath 被删除文件的文件�??
     * @return 单个文件删除成功返回true，否则返回false
     */
    public static boolean deleteFile(String sPath) {
        boolean flag = false;
        File file = new File(sPath);
        // 路径为文件且不为空则进行删除
        if (file.isFile() && file.exists()) {
            file.delete();
            flag = true;
        }
        return flag;
    }

    public static String getRealFilePath(final Uri uri, final Context ctx) {
        if (null == uri)
            return null;
        final String scheme = uri.getScheme();
        String data = null;
        if (scheme == null)
            data = uri.getPath();
        else if (ContentResolver.SCHEME_FILE.equals(scheme)) {
            data = uri.getPath();
        } else if (ContentResolver.SCHEME_CONTENT.equals(scheme)) {
            Cursor cursor = ctx.getContentResolver().query(uri, new String[]{ImageColumns.DATA}, null, null, null);
            if (null != cursor) {
                if (cursor.moveToFirst()) {
                    int index = cursor.getColumnIndex(ImageColumns.DATA);
                    if (index > -1) {
                        data = cursor.getString(index);
                    }
                }
                cursor.close();
            }
        }
        return data;
    }

    public static boolean isOpenGps(Context context) {
        LocationManager locationManager = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);
        return locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
    }

    // 捆绑安装
    public static boolean retrieveApkFromAssets(Context context, String fileName, String path) {
        boolean bRet = false;

        try {
            File file = new File(path);
            if (file.exists()) {
                return true;
            } else {
                file.createNewFile();
                InputStream is = context.getAssets().open(fileName);
                FileOutputStream fos = new FileOutputStream(file);

                byte[] temp = new byte[1024];
                int i = 0;
                while ((i = is.read(temp)) != -1) {
                    fos.write(temp, 0, i);
                }
                fos.flush();
                fos.close();
                is.close();

                bRet = true;
            }

        } catch (IOException e) {
            e.printStackTrace();
        }
        return bRet;
    }

    public static boolean isAppInstalled(Context context, String packagename) {
        PackageInfo packageInfo;
        try {
            packageInfo = context.getPackageManager().getPackageInfo(packagename, 0);
        } catch (NameNotFoundException e) {
            packageInfo = null;
            e.printStackTrace();
        }
        // System.out.println("没有安装");
        // System.out.println("已经安装");
        return packageInfo != null;
    }

    public static Toast showToast(String tvStr) {
        if (toast2 == null) {
            toast2 = new Toast(MyApplication.applicationContext);
        }
        View view = LayoutInflater.from(MyApplication.applicationContext).inflate(R.layout.toast_custom, null);
        TextView tv = (TextView) view.findViewById(R.id.toast_custom_tv);
        tv.setText(tvStr);
        toast2.setView(view);
        toast2.setGravity(Gravity.CENTER_VERTICAL, 0, 0);
        toast2.show();
        return toast2;
    }

    public static String getLeixing(Context context, String yy, String name) {

        String nameL = name.trim();
        Resources res = context.getResources();
        if (!yy.equals("zh")) {
            if (name.equals("裁断")) {
                nameL = res.getString(R.string.caiduan);
            } else if (name.equals("针车")) {
                nameL = res.getString(R.string.zhenche);
            } else if (name.equals("组底")) {
                nameL = res.getString(R.string.zudi);
            } else if (name.equals("成型")) {
                nameL = res.getString(R.string.chengxing);
            } else if (name.equals("线外加工")) {
                nameL = res.getString(R.string.jiagong);
            } else if (name.isEmpty() || name.equals("未知")) {
                nameL = res.getString(R.string.wz_0);
            } else if (name.equals("前掌内腰")) {
                nameL = res.getString(R.string.wz_1);
            } else if (name.equals("右前掌内腰")) {
                nameL = res.getString(R.string.wz_2);
            } else if (name.equals("右前掌外腰")) {
                nameL = res.getString(R.string.wz_3);
            } else if (name.equals("右鞋头")) {
                nameL = res.getString(R.string.wz_4);
            } else if (name.equals("右鞋跟")) {
                nameL = res.getString(R.string.wz_5);
            } else if (name.equals("右鞋身内腰")) {
                nameL = res.getString(R.string.wz_6);
            } else if (name.equals("右鞋身外腰")) {
                nameL = res.getString(R.string.wz_7);
            } else if (name.equals("左前掌内腰")) {
                nameL = res.getString(R.string.wz_8);
            } else if (name.equals("左前掌外腰")) {
                nameL = res.getString(R.string.wz_9);
            } else if (name.equals("左鞋头")) {
                nameL = res.getString(R.string.wz_10);
            } else if (name.equals("左鞋跟")) {
                nameL = res.getString(R.string.wz_11);
            } else if (name.equals("左鞋身内腰")) {
                nameL = res.getString(R.string.wz_12);
            } else if (name.equals("左鞋身外腰")) {
                nameL = res.getString(R.string.wz_13);
            }
        }
        return nameL;
    }

}
